<template>
  <div class="order-page">
    <v-title :title="$route.meta.title" />
    <loading :show="loading" :timeout="loadingTimeout" />
    <div class="pay" v-if="!loading && Object.keys(this.params).length > 0">
      <cube-button primary @click="goPay()">
        <!--      <cube-button primary @click="goMode()">-->
        {{ !active_code && +amount > 0 && !offline ? `立即支付(￥${+amount})` : '确认下单' }}
      </cube-button>
    </div>
    <remark @remark="changeRemark" />
    <active @remark="changeActive" v-if="is_active && false" />
    <product-cart :list="currentProducts" />
    <store :list="storeList" @selectedStore="selectedStore" v-if="false" />
    <div class="discount" v-if="showDiscount">
      <div class="title">让利(%百分比):</div>
      <cube-input v-model="discount" />
    </div>
    <v-address
      :discount="showDiscount"
      :address="addressList"
      @hideAddress="hideAddress"
      @selectedAddress="selectedAddress"
      v-if="+this.check_store !== 2"
    />
    <div class="mode" v-if="+amount > 0">
      <template v-if="onlyOffline">
        <cube-checkbox v-model="offline" class="offline" @input="listenOffline" :option="{disabled: true}">
          <span>线下打款</span>
        </cube-checkbox>
      </template>
      <template v-else>
        <cube-checkbox v-model="offline" class="offline" @input="listenOffline">
          <span>线下打款</span>
        </cube-checkbox>
      </template>
    </div>
    <calc :total="showTotal" />
    <account :account="account" />
    <pay :amount="amount" />
  </div>
</template>

<script>
import Title from '@/components/Title'
import Loading from '@/components/Loading'
import base64 from '@/util/base64'
import api from '@/api'
import Account from './components/Account'
import Address from './components/Address'
import ProductCart from './components/ProductCart'
import Calc from './components/Calc'
import Pay from './components/Pay'
import Remark from './components/Remark'
import Active from './components/Active'
import Store from './components/Store'
export default {
  name: 'Order',
  components: {
    Loading,
    'v-title': Title,
    ProductCart,
    'v-address': Address,
    Account,
    Calc,
    Pay,
    Remark,
    Active,
    Store
  },
  computed: {
    // 云仓总数量
    // storeTotal() {
    //   let sum = 0
    //   this.productList.forEach(x => {
    //     sum += +x.store
    //   })
    //   return sum
    // },
    // calc products
    currentProducts() {
      let list
      if (!this.params.cart) {
        list = [this.productList]
      } else {
        // cart to product
        list = []
        this.productList.forEach(item => {
          const obj = item.product
          obj.sku = item.sku
          obj.quantity = item.quantity
          if (item.selected_sku_text) {
            obj.selected_sku_text = item.selected_sku_text
          }
          list.push(obj)
        })
      }
      return list
    },
    // show total
    showTotal() {
      const total = {
        freight: 0,
        price: 0,
        score: 0,
        platform_ticket: 0,
        // 新加的运费
        f: 0
      }
      const list = this.currentProducts
      let freight = 0
      let price = 0
      let score = 0
      let f = 0
      list.forEach(x => {
        // console.log(x)
        f += x.quantity * x.freight
        if (this.remoteCity) {
          freight += x.quantity * x.remote_freight
        }
        freight += f
        if (x.area && x.area[0] && +x.area[0].area_id === 2 && +x.f > 0) {
          // price += x.quantity * x.scoreCost.total
          if (x.sku) {
            score += x.quantity * x.sku.price
          } else {
            score += x.quantity * x.price
          }
        } else {
          if (x.sku) {
            price += x.quantity * x.sku.price
          } else {
            price += x.quantity * x.price
          }
        }
      })
      total.freight = freight.toFixed(2)
      total.price = price.toFixed(2)
      total.score = score.toFixed(2)
      return total
    },
    // pay money
    amount() {
      let total = +this.showTotal.price + +this.showTotal.freight
      // console.log('freight: ', this.showTotal.freight)
      if (+this.account.score < +this.showTotal.score) {
        total += +this.showTotal.score - +this.account.score
      }
      const use = +this.account.score + +this.account.balance
      let amount = total - use
      if (amount < 0) {
        amount = 0
      }
      return +Number.parseFloat(amount).toFixed(2)
    }
  },
  data() {
    return {
      loading: false,
      loadingTimeout: 10,
      params: {},
      account: {},
      productList: [],
      addressList: [],
      remoteCity: false,
      // pay mode
      offline: false,
      onlyOffline: false,
      remark: '',
      active_code: '',
      // 是否可以使用激活码支付
      is_active: false,
      // 云仓选择
      storeList: [
        {id: 1, value: 1, label: '直接发货', selected: true},
        {id: 2, value: 2, label: '放入云仓', selected: false},
      ],
      check_store: 1,
      store_num: 0,
      // 让利
      discount: 20,
      showDiscount: false
    }
  },
  methods: {
    // 输入激活码支付
    changeActive(v) {
      // console.log(v)
      this.active_code = v
      // if (v && v.length > 1) {
      //   this.amount = 0
      // }
    },
    changeRemark(v) {
      this.remark = v
    },
    listenOffline() {
      // console.log(this.offline)
    },
    getProduct() {
      this.loading = true
      api.Order.getProduct({ ...this.params }).then(response => {
        let { data } = response
        data = base64.parse(data)
        this.productList = data.list
        this.is_active = data.is_active
        // 进云仓数据
        this.store_num = data.store
        // console.log(this.productList)
        if (this.productList.area) {
          const area = this.productList.area[0].area_id
          this.showDiscount = +area === 9
        }
        if (this.store_num <= 0) {
          this.storeList = [this.storeList[0]]
        }
      }).then(() => {
        this.loading = false
      })
    },
    getAccount() {
      this.loading = true
      api.Order.getAccount().then(response => {
        let { data } = response
        data = base64.parse(data)
        this.account = data
      }).finally(() => {
        this.loading = false
      })
    },
    getAddress() {
      this.loading = true
      api.Order.getAddress().then(response => {
        let { data } = response
        data = base64.parse(data)
        this.addressList = data
        // selected
        this.addressList.forEach((v, k) => {
          if (k === 0) {
            this.$set(v, 'selected', true)
            this.isRemoteCity(v.province_id)
          } else {
            this.$set(v, 'selected', false)
          }
        })
      }).finally(() => {
        this.loading = false
      })
    },
    parseParams() {
      /**
       * refresh => nothing
       */
      return new Promise(resolve => {
        const p = this.$route.params
        if (Object.keys(p).length === 0) {
          this.params = this.$store.getters['ExeOrder/params']
          resolve()
        } else {
          this.$store.dispatch('ExeOrder/set_params', p).then(() => {
            this.params = p
            resolve()
          })
        }
      })
    },
    /**
     * hide more address
     * sort selected address
     */
    hideAddress() {
      setTimeout(() => {
        this.addressList.sort((x, y) => {
          return (+y.selected) - (+x.selected)
        })
      }, 100)
    },
    selectedAddress(item) {
      this.addressList.forEach(x => {
        if (x.id === item.id) {
          this.$set(x, 'selected', true)
          this.isRemoteCity(x.province_id)
        } else {
          this.$set(x, 'selected', false)
        }
      })
    },
    isRemoteCity(province_id) {
      this.loading = true
      api.Order.isRemoteCity({ province_id }).then(response => {
        let { data } = response
        data = base64.parse(data)
        this.remoteCity = data.result
      }).finally(() => {
        this.loading = false
      })
    },
    selectedStore(item) {
      this.storeList.forEach(x => {
        if (x.id === item.id) {
          this.$set(x, 'selected', true)
          this.check_store = item.value
        } else {
          this.$set(x, 'selected', false)
        }
      })
    },
    // goMode() {
    //   if (!this.offline) {
    //     this.goPay()
    //   } else {
    //     return this.$createToast({
    //       type: 'correct',
    //       time: 1000,
    //       txt: '下单成功',
    //       onTimeout: () => {
    //         this.$router.push('/service/order/2')
    //       }
    //     }).show()
    //   }
    // },
    goPay() {
      if (this.showDiscount) {
        if (!this.discount || isNaN(this.discount) || +this.discount <= 0) {
          return this.$createToast({
            type: 'error',
            time: 500,
            txt: '请填写正确的让利',
            onTimeout: () => {
            }
          }).show()
        }
      }
      if (this.addressList.length === 0) {
        return this.$createToast({
          type: 'error',
          time: 500,
          txt: '请添加收货地址',
          onTimeout: () => {
            this.$router.push('/service/address-edit/-2')
          }
        }).show()
      }
      // 云仓选择
      const store = this.storeList.filter(x => x.selected)
      if (store.length === 0) {
        return this.$createToast({
          type: 'error',
          time: 500,
          txt: '请选择收货方式',
          onTimeout: () => {
          }
        }).show()
      }
      // const store_id = store[0].id
      // 地址选择处理
      const address = this.addressList.filter(x => x.selected)
      if (address.length === 0 && +this.check_store !== 2) {
        return this.$createToast({
          type: 'error',
          time: 500,
          txt: '请选择收货地址',
          onTimeout: () => {
          }
        }).show()
      }
      const address_id = (address && address[0] && address[0].id) || 0
      this.loading = true
      api.Order.createOrder({
        ...this.params,
        address_id,
        offline: this.offline,
        remark: this.remark,
        active_code: this.active_code,
        // 云仓
        check_store: this.check_store,
        store_num: this.store_num,
        discount: this.discount
      }).then(response => {
        // clear params
        this.$store.dispatch('ExeOrder/set_params', {}).then()
        let { data } = response
        data = base64.parse(data)
        // offline pay
        if (this.offline) {
          return this.$createToast({
            type: 'correct',
            time: 1000,
            txt: '下单成功',
            onTimeout: () => {
              this.$router.push('/service/order/2')
            }
          }).show()
        } else if (+data.amount === 0) {
          return this.$createToast({
            type: 'correct',
            time: 1000,
            txt: '支付成功',
            onTimeout: () => {
              if (data.is_create) {
                this.$router.push('/service/group/0')
              } else if (data.is_join_random) {
                this.$router.push('/service/group/1')
              } else {
                // this.$router.push('/service/order/3')
                this.$router.push('/service/order/0')
              }
            }
          }).show()
        }
        const serial = {
          order_id: data.order_id
        }
        // console.log(serial)
        this.$router.push(`/pay/${base64.encode(serial)}`)
        // this.$router.replace(`/pay/${base64.encode(serial)}`)
      }).catch(error => {
        this.$createToast({
          type: 'warn',
          txt: error.message,
          time: 1000,
          onTimeout: () => {
            // this.$router.back()
          }
        }).show()
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * check referrer
     */
    checkReferrer() {
      api.Order.checkReferrer().then(response => {
        let { data } = response
        data = base64.parse(data)
        if (!data.result) {
          return this.$createToast({
            type: 'warn',
            txt: '您没有推荐人,不能下单!',
            time: 1000,
            onTimeout: () => {
              // this.$router.push('/')
              this.$router.back()
            }
          }).show()
        }
      })
    },
    /**
     * check second kill
     */
    checkSecondKill() {
      const p = this.$route.params
      if (p.product_id && +p.product_id > 0) {
        api.Order.checkSecondKill({ product_id: p.product_id }).then(() => {}).catch(err => {
          return this.$createToast({
            type: 'warn',
            txt: err.message,
            time: 1000,
            onTimeout: () => {
              this.$router.back()
            }
          }).show()
        })
      }
    },
    /**
     * check group join
     */
    checkGroup() {
      const p = this.$route.params
      if (p.group_id && +p.group_id > 0) {
        api.Order.checkGroup({ group_id: p.group_id }).then(() => {}).catch(err => {
          return this.$createToast({
            type: 'warn',
            txt: err.message,
            time: 1000,
            onTimeout: () => {
              this.$router.back()
            }
          }).show()
        })
      }
    }
  },
  created () {
    // offline pay
    if (this.$store.getters['System/offlinePay']) {
      this.offline = true
      this.onlyOffline = true
    } else {
      this.offline = false
      this.onlyOffline = false
    }
    this.checkReferrer()
    this.checkGroup()
    this.checkSecondKill()
    this.parseParams().then(() => {
      if (Object.keys(this.params).length === 0) {
        // return this.$createToast({
        //   type: 'warn',
        //   txt: '订单已生成,请勿重复提交',
        //   time: 1000,
        //   onTimeout: () => {
        //     this.$router.push('/')
        //   }
        // }).show()
        return this.$router.replace('/')
      }
      this.getProduct()
      this.getAccount()
      this.getAddress()
      // debug
      if (process.env.NODE_ENV === 'dev') {
        /*
         * {"cart":true}
         *
         * {"price":"599.00","product_id":"141","quantity":1}
         *
         * {"quantity":5,"price":"7777777.00","score_cost":"100.00",
         * "product_sku_id":"20","selected_sku_value":["43","48","50"],
         * "selected_sku_text":["红色","中","加厚"],"product_id":"149"}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"create_group":true}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"random_group":true}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"group_id":"44"}
         *
         * {"quantity":5,"price":"399.00","score_cost":0,
         * "product_sku_id":"12","selected_sku_value":["16","18"],
         * "selected_sku_text":["bbb","ccc"],"product_id":"148","create_group":true}
         *
         * {"quantity":5,"price":"399.00","score_cost":0,
         * "product_sku_id":"12","selected_sku_value":["16","18"],
         * "selected_sku_text":["bbb","ccc"],"product_id":"148","group_id":"44"}
         */
        // console.log(JSON.stringify(this.params))
      }
    })
  }
}
</script>

<style scoped lang="stylus">
.order-page
  padding-top 45px
  padding-bottom 55px
  .discount
    margin 10px
    padding 10px
    background white
    border-radius 10px
    text-align left
    min-height 60px
    display flex
    flex-direction column
    justify-content space-around
    .title
      font-weight 700
      padding-bottom 10px
  .pay
    position fixed
    z-index 100
    width 100%
    bottom 0
  .mode
    background white
    margin 10px
    border-radius 10px
    .offline
      font-size 18px
      span
        font-size 14px
        vertical-align center
        color $main_color
</style>
